package com.note.back.service;

import com.note.back.mapper.CategoryMapper;
import com.note.back.pojo.Category;
import com.note.back.pojo.User;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class LLMService {
    private static final String BASE_URL = "https://api.deepseek.com";
    private static final String API_KEY = "sk-190e1e56ab334396963fce2673b13085";

    @Autowired
    CategoryMapper categoryMapper;

    //续写
    public String continuation(String note) throws IOException {
        String question = note + "\n以上是我的笔记内容，请帮我进行续写，不需要其他的内容（比如回应词），只需回答续写的内容即可";
        return dealQuestion(question);
    }

    //分类
    public String categorize(User author, String note) throws IOException {
        List<Category> categories = categoryMapper.list(author.getId());
        String categoryName = "";
        for (Category category : categories) {
            categoryName += "id: " + category.getId() + ", 名称: " + category.getName() + ";\n";
        }

        String question = note + "\n以上是我的笔记内容，能帮我在下面的笔记分类中，选择一个最符合的吗\n笔记种类:" + categoryName+"（只需要输出种类id，不需要理由，不需要回应词，只要一个数字）";
        return dealQuestion(question);
    }

    public String dealQuestion(String question) throws IOException{
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();

        message.put("content",question);
        message.put("role","user");
        messages.put(message);

        return LLMResponse(messages);
    }

    //获取回复
    public String LLMResponse(JSONArray messages) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        //请求头
        String url = BASE_URL + "/chat/completions";
        JSONObject body = new JSONObject();
        body.put("messages",messages);
        body.put("model","deepseek-chat");
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), body.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();

        //解析大模型回复
        Response response = client.newCall(request).execute();
        int statusCode = response.code();
        if (statusCode != 200) {
            return Integer.toString(statusCode);
        }else {
            JSONObject jsonResponse = new JSONObject(response.body().string());
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject JSONmessage = choice.getJSONObject("message");
                String content = JSONmessage.getString("content");
                return content;
            }
            return null;
        }
    }
}
